<?php
	require_once("lib/classes/EncuentroTorneo.php"); 
	require_once("lib/inc_comments.php");
	$id = REPLACE_Injection(@$_GET["id"]);
	$action = REPLACE_Injection(@$_GET["action"]);	
	$partido = new EncuentroTorneo(0, 0, 0, $id);
	$data = $partido->getMatchFromDB();
	$allowedToPostMatchComment = isAllowedToPostMatchComments($data);	
	$reportAbuseAction = FALSE;
	$error = "";
	$ok = "";
	if($action == "post-comment"){
		if(checkActionTime()){
			$text = utf8_encode(strip_tags(REPLACE_Injection($_POST["comment"])));
			if(strlen($text) > 0){
				if($allowedToPostMatchComment){
					$values = array("NULL", $_SESSION["user_id"], time(), $text, 0, "", $id);
					$insert = new mysqlInsert("tournament", "", "comentarios_partido", $values);
					$insert->execute();
					/* FILES */				
					$commentId = $insert->getInsertedId();
					$img = $commentId;								
					$imgId = processImage(	IMG_MAX_ALLOWED_SIZE, 
																IMG_PATH.IMG_COMMENTS_PATH, 
																IMG_PATH.IMG_COMMENTS_PATH.IMG_THUMBNAIL_PATH, 
																IMG_THUMBNAIL_WIDTH, 
																$img, 
																"image", 
																NULL);
					
					if($imgId != 0){					
						if($imgId > 0){
							$fields = array("imagen");
							$values = array($imgId);
							$update = new mysqlUpdate("tournament", "", "comentarios_partido", $fields, $values, "`id`='".$commentId."'");
							$update->execute();
						}else{					
							$delete = new mysqlDelete("tournament", "", "comentarios_partido", "`id`='".$commentId."'");
							$delete->execute();
		
							if($imgId == -1)
								$error = "The uploaded picture has a not valid format. Use only JPG or PNG files";
							elseif($imgId == -2)
								$error = "An unexpected error has ocurred, please try again later or post in the correct forum this bug";						
						}
					}
					
					if(empty($error)){
						$u = "UPDATE `partido_torneo` SET comentarios = comentarios + 1 WHERE `id`='".$id."'";
						$update = new mysqlUpdate("tournament", $u, "", "", "", "");
						$update->execute();
						$ok = "Your comment has been posted";
						refreshActionTime();
						addKarmaComment($_SESSION["user_id"]);
					}
				}else{
					$error = "You are not allowed to post comments in this match";
				}
			}else{
				$error = "You have to fill the comment text to post it!";
			}
		}else{
			$error = "You have to wait ".getCurrentActionTime()." minutes to post another comment";
		}
	}else if($action == "report-abuse"){
		$reportAbuseAction = TRUE;
	}else if($action == "report-abuse-post"){		
		$text = utf8_encode(strip_tags(REPLACE_Injection($_POST["complaint"])));
		$acusado = utf8_encode(strip_tags(REPLACE_Injection($_POST["who"])));
		$imagen = "";
		$video = "";
		if(strlen($text) > 0){
			if($allowedToPostMatchComment){
				$values = array("NULL", $id, $_SESSION["user_id"], $acusado, $text, 0, $video, 0, 0, time(), time(), 0);
				$insert = new mysqlInsert("tournament", "", "complaint_partido", $values);
				$insert->execute();
				$complaintId = $insert->getInsertedId();

				$img = $complaintId;				
				$imgId = processImage(	IMG_MAX_ALLOWED_SIZE, 
															IMG_PATH.IMG_COMPLAINTS_PATH, 
															IMG_PATH.IMG_COMPLAINTS_PATH.IMG_THUMBNAIL_PATH, 
															IMG_THUMBNAIL_WIDTH, 
															$img, 
															"image", 
															NULL);
	
				if($imgId != 0){					
					if($imgId > 0){
						$fields = array("imagen");
						$values = array($imgId);
						$update = new mysqlUpdate("tournament", "", "complaint_partido", $fields, $values, "`id`='".$complaintId."'");
						$update->execute();
					}else{
						$delete = new mysqlDelete("tournament", "", "complaint_partido", "`id`='".$complaintId."'");
						$delete->execute();
						
						if($imgId == -1)
							$error = "The uploaded picture has a not valid format. Use only JPG or PNG files";
						elseif($imgId == -2)
							$error = "An unexpected error has ocurred, please try again later or post in the correct forum this bug";
					}
				}

				if(empty($error)){
					$ok = "Your complaint has been sent.";
				}
			}else{
				$error = "You are not allowed to post complaints in this match";
			}
		}else{
			$reportAbuseAction = TRUE;
			$error = "You have to fill the obligatory fields";
		}
	}else if($action == "set-match-score"){
		if($allowedToPostMatchComment){
			$g1 = REPLACE_Injection($_POST["g1"]);
			$g2 = REPLACE_Injection($_POST["g2"]);
			if(is_numeric($g1) && is_numeric($g2)){
				if($g1 >= 0 && $g1 < 50 && $g2 >= 0 && $g2 < 50){					
					$ret = apuntarPartido($id, $g1, $g2);
					if($ret === FALSE){
						$error = "An error has ocurred. Match is not available.";
					}else{
						if($data["ida_vuelta"] == 0){
							$ok = "Match score has been set. Wait for a moderator to validate it.";
							$data["goles_equipo1"] = $g1 + $data["goles_equipo1_aux"];
							$data["goles_equipo2"] = $g2 + $data["goles_equipo2_aux"];
							$data["estado"] = MATCH_STATUS_SCORED;
						}else{
							$idaVueltaGanador = -1;
							if(is_array($ret)){
								$idaVueltaGanador = $ret[1];
								$ret = $ret[0];
							}
							switch($ret){
								case MATCH_STATUS_SCORED:								
									$ok = "Match score has been set. Wait for a moderator to validate it.";
									$data["goles_equipo1"] = $g1 + $data["goles_equipo1_aux"];
									$data["goles_equipo2"] = $g2 + $data["goles_equipo2_aux"];
									if($idaVueltaGanador != -1)
										$data["ganador"] = $idaVueltaGanador;
									$data["estado"] = MATCH_STATUS_SCORED;
									break;
								case MATCH_STATUS_RETURN_WAIT:
									$ok = "Match score has been set. Get ready now for the return match.";
									$data["goles_equipo1_aux"] = $g1 + $data["goles_equipo1_aux"];
									$data["goles_equipo2_aux"] = $g2 + $data["goles_equipo2_aux"];
									$data["estado"] = MATCH_STATUS_RETURN_WAIT;
									break;
								case MATCH_STATUS_RETURN_DRAW: 
									$ok = "Match score has been set. There is a draw. 2 More matches needed to be played";
									$data["goles_equipo1_aux"] = $g1 + $data["goles_equipo1_aux"];
									$data["goles_equipo2_aux"] = $g2 + $data["goles_equipo2_aux"];
									$data["estado"] = MATCH_STATUS_RETURN_DRAW;
									break;
							}
						}						
					}
				}else{
					$error = "Goals are invalid";
				}
			}else{
				$error = "Goals must be numeric!";
			}
		}else{
			$error = "You are not allowed to set this match score";
		}
	}else if($action == "upload-screenshot"){
		if($allowedToPostMatchComment){
			$type = REPLACE_Injection($_POST["screenshot-type"]);
			if($type > 0 && $type < 6){
				$img = $id.substr(md5(time()), strlen(md5(time())) - 5,5);
				$imgId = processImage(	IMG_MAX_ALLOWED_SIZE, 
								IMG_PATH.IMG_MATCH_PATH, 
								IMG_PATH.IMG_MATCH_PATH.IMG_THUMBNAIL_PATH, 
								IMG_THUMBNAIL_WIDTH, 
								$img, "image", 
								NULL);
				if($imgId != 0){
					if($imgId > 0){
						$values = array($imgId, $id, time(), $_SESSION["user_id"], $type);
						$insert = new mysqlInsert("tournament", "", "partido_images", $values);
						$insert->execute();
						$ok = "Your screenshot has been saved";
					}else{						
						if($imgId == -1)
							$error = "The uploaded picture has a not valid format. Use only JPG or PNG files";
						elseif($imgId == -2)
							$error = "An unexpected error has ocurred please try again later or post a bug in the correct forum";
					}
				}else{
					$error = "You have to upload a screenshot";
				}
			}else{
				$error = "Invalid Type";
			}
		}
	}
	
	if($data){
		?>
		<div id="all-tournament">
			<div class="container-match-header">
				<div id="header-match">
					<div class="team-name-1"><?php echo $data["e1equiponombre"];?></div>
					<div class="team-name-2"><?php echo $data["e2equiponombre"];?></div>
					<img src="team-logos/Deportivo.png" class="logo-team-1" width="128" height="128" />
					<img src="team-logos/Espanyol.png" class="logo-team-2" width="128" height="128" />
					<div class="team-player-names-1">
						<?php echo $data["e1j1nombre"];?>
						<?php if(!is_null($data["e1j2nombre"])){ echo "<br/>".$data["e1j2nombre"]; }?>
					</div>
					<div class="team-player-names-2">					
						<?php echo $data["e2j1nombre"];?>
						<?php if(!is_null($data["e2j2nombre"])){ echo "<br/>".$data["e2j2nombre"]; }?>
					</div>
					<?php
					if($data["estado"] == MATCH_STATUS_SCORED && isAdmin()){
								echo '<div id="admin-match-links">';
								echo '<a href="index.php?s=match-management&id='.$data["id"].'&a=1" class="match-admin">Validate Match</a>';
								echo '<a href="index.php?s=match-management&id='.$data["id"].'&a=2&team='.$data["e1"].'" class="match-admin">Disqualify '.$data["e1equiponombre"].'</a>';
								echo '<a href="index.php?s=match-management&id='.$data["id"].'&a=2&team='.$data["e2"].'" class="match-admin">Disqualify '.$data["e2equiponombre"].'</a>';
								echo '</div>';
					}
					
					if($allowedToPostMatchComment){
						if($data["ida_vuelta"] == 0){
							if($data["estado"] == MATCH_STATUS_SCORED || $data["estado"] == MATCH_STATUS_VALIDATED){
								echo '<div class="team-result-1">'.$data["goles_equipo1"].'</div>';
								echo '<div class="team-result-2">'.$data["goles_equipo2"].'</div>';														
							}else if($data["estado"] == MATCH_STATUS_SCHEDULED && $allowedToPostMatchComment){								
								echo '<form id="score" action="index.php?s=match&id='.$id.'&action=set-match-score" method="POST">';
								echo '<input type="text" class="team-result-input-1" maxlength="2" size="2" name="g1"/>';
								echo '<input type="text" class="team-result-input-2" maxlength="2" size="2" name="g2"/>';
								echo '<input type="submit" value="Send Score" class="submit-match-score"/>';							
								echo '</form>';
							}
						}else{
							if($data["estado"] == MATCH_STATUS_SCORED || $data["estado"] == MATCH_STATUS_VALIDATED){
								if($data["ganador"]){
									if($data["ganador"] == 1){
										echo '<div class="team-result-1-ganador">'.$data["goles_equipo1"].'</div>';
										echo '<div class="team-result-2">'.$data["goles_equipo2"].'</div>';
									}else if($data["ganador"] == 2){
										echo '<div class="team-result-1">'.$data["goles_equipo1"].'</div>';
										echo '<div class="team-result-2-ganador">'.$data["goles_equipo2"].'</div>';
									}
								}else{
									if($data["goles_equipo1"] == $data["goles_equipo2"]){
										if($data["goles_equipo1_aux"] == 1 && $data["goles_equipo2_aux"] == 0){
											echo '<div class="team-result-1-ganador">'.$data["goles_equipo1"].'</div>';
											echo '<div class="team-result-2">'.$data["goles_equipo2"].'</div>';
										}else if($data["goles_equipo2_aux"] == 1 && $data["goles_equipo1_aux"] == 0){
											echo '<div class="team-result-1">'.$data["goles_equipo1"].'</div>';
											echo '<div class="team-result-2-ganador">'.$data["goles_equipo2"].'</div>';
										}
									}else{
										echo '<div class="team-result-1">'.$data["goles_equipo1"].'</div>';
										echo '<div class="team-result-2">'.$data["goles_equipo2"].'</div>';
									}
								}										
							}else if($data["estado"] == MATCH_STATUS_SCHEDULED && $allowedToPostMatchComment){								
								echo '<form id="score" action="index.php?s=match&id='.$id.'&action=set-match-score" method="POST">';
								echo '<input type="text" class="team-result-input-1" maxlength="2" size="2" name="g1"/>';
								echo '<input type="text" class="team-result-input-2" maxlength="2" size="2" name="g2"/>';
								echo '<input type="submit" value="Send Score" class="submit-match-score"/>';							
								echo '</form>';
							}else if($data["estado"] == MATCH_STATUS_RETURN_WAIT && $allowedToPostMatchComment){
								echo '<div class="team-result-aux-text">First Leg Result</div>';
								echo '<div class="team-result-1-aux">'.$data["goles_equipo1_aux"].'</div>';
								echo '<div class="team-result-2-aux">'.$data["goles_equipo2_aux"].'</div>';
								echo '<form id="score" action="index.php?s=match&id='.$id.'&action=set-match-score" method="POST">';
								echo '<input type="text" class="team-result-input-1" maxlength="2" size="2" name="g1"/>';
								echo '<input type="text" class="team-result-input-2" maxlength="2" size="2" name="g2"/>';
								echo '<input type="submit" value="Send Score" class="submit-match-score"/>';							
								echo '</form>';
							}else if($data["estado"] == MATCH_STATUS_RETURN_DRAW && $allowedToPostMatchComment){
								echo '<div class="team-result-aux-text">Latest Couple of Matches Result</div>';
								echo '<div class="team-result-1-aux">'.$data["goles_equipo1_aux"].'</div>';
								echo '<div class="team-result-2-aux">'.$data["goles_equipo2_aux"].'</div>';
								echo '<form id="score" action="index.php?s=match&id='.$id.'&action=set-match-score" method="POST">';
								echo '<input type="text" class="team-result-input-1" maxlength="2" size="2" name="g1"/>';
								echo '<input type="text" class="team-result-input-2" maxlength="2" size="2" name="g2"/>';
								echo '<input type="submit" value="Send Score" class="submit-match-score"/>';							
								echo '</form>';
							}
						}
					}
					?>
				</div>
			</div>	
			<div id="left-tournament">			
				<?php			
					if(strlen($error) > 0){
						echo '<div id="error">'.$error.'</div>';
					}
					if(strlen($ok) > 0){
						echo '<div id="ok">'.$ok.'</div>';
					}
				?>	
				
				<?php
					$screenshots = mostrarAttachedScreenshots($id);			
				
					if(!$reportAbuseAction){						
				?>
				<h1>Comments in this match</h1>		
				<div class="container-tournament">
				<?php mostrarComentariosPartido($id);?>
				</div>
				<?php
					}
					 
				if($allowedToPostMatchComment){
					if($reportAbuseAction){
						?>
						<h1>Leave your complaint</h1>						
						<div class="container-tournament">
							<p><strong>Read carefully before you complaint:</strong></p>
							<p>If you want to complaint because a player is not following the rules, 
							is cheating or does not respect you, <strong>send a complaint</strong> to the moderators.</p>
							<p>Fake, useless, clueless, incomplete or weird complaints can be punished with warning or ban.</p>
							<p>Try to be clear and focus on what you want to complaint. Any discussion will start from this complaint. Moderators will only take decisions on the facts that have happened.</p>
							<p>A conversation thread will be open in "Your complaints" section with the current status of your complaint</p>
							<form action="index.php?s=match&id=<?php echo $id;?>&action=report-abuse-post" method="post" enctype="multipart/form-data">
								<div class="comment-form">
								<p>Who are you complaining to?</p>
								<input type="text" name="who" size="30" maxlength="255" /><br/>
								<p>Upload a Picture (optional)</p>
								<input type="file" name="image" size="30" /><br/>
								<p>Link a video from Youtube, Vimeo, or others (optional)</p>
								<input type="text" name="video" size="30" maxlength="255" /><br/>
								<p>Complaint Description</p>
								<textarea cols="63" rows="6" name="complaint"></textarea><br/>
								<input type="submit" value="Send Complaint" class="boton"/>
								</div>
							</form>	
						</div>
						<?php
					}else{
						?>
						<h1>Leave your comment</h1>
						<div class="container-tournament">
							<form action="index.php?s=match&id=<?php echo $id;?>&action=post-comment" method="post" enctype="multipart/form-data">
								<div class="comment-form">
								<p>Your comment</p>								
								<textarea cols="63" rows="6" name="comment"></textarea><br/>
								<p>Link to an uploaded video (Optional)</p>
								<input type="text" size="30" maxlength="255" name="video"/><br/>
								<p>Upload a picture (Optional)</p>
								<input type="file" size="30" name="image"/><br/>
								<input type="submit" value="Send Comment" class="boton"/>
								</div>
							</form>	
						</div>
						<?php
					}
				}				
				?>
				
			</div>
			<div id="right-tournament">				
				<h1>Player Information</h1>
				<div class="container-tournament" style="border:0;">
				<?php
				mostrarInformacionJugadoresPartido($id);
				?>	
				</div>
				<h1>Global Teams Information</h1>
				<div class="container-tournament" style="border:0;">
				<?php
				mostrarInformacionEquiposPartido($id);
				?>	
				</div>
				<h1>Screenshots</h1>
				<div class="container-tournament">
				<?php 
					if($screenshots){
					?>
					<p>There are <strong><?php echo $screenshots;?> screenshot(s)</strong> attached. <br/><a href="#" onclick="document.getElementById('screenshots-list').style.display = 'inline';">Show screenshots</a></p>
					<?php
					}
				?>					
					<p>Upload screenshots attached to this match here.</p>
					<p>Remember that, to let moderators validate your match there must be at least <strong>2 screenshots</strong> attached to the match:</p>
					<p>
							<strong>1.</strong> Where players agree to play a tournament match.<br/>
							<strong>2.</strong> The last screen where the score is shown.
					</p>
					<div style="padding: 0px 10px 5px 10px;">
					<form class="form" style="border: 0;" action="index.php?s=match&id=<?php echo $id;?>&action=upload-screenshot" method="post" enctype="multipart/form-data" name="screenshot" id="screenshot">
						<input type="file" name="image"/><br/><br/>
						<select name="screenshot-type">
							<option value="0">Screenshot Type</option>
							<option value="1">Configuration Screenshot</option>
							<option value="2">Match Agreement Screenshot</option>
							<option value="3">In-match Screenshot</option>
							<option value="4">Chat Screenshot</option>
							<option value="5">Score Screenshot</option>
						</select><br/><br/>
						<input type="submit" value="Upload" class="boton" style="float:none;"/>
					</form>
					</div>
					<p>Remember to take screenshots of everything. But if you want to complaint, 
					<a href="index.php?s=match&id=<?php echo $id;?>&action=report-abuse">use the complaint form</a>. 
					In other case, your complaint won't be reviewed.</p>
				</div>
				<h1>Complaints</h1>
				<div class="container-tournament">
					<p>If you want to complaint because a player is not following the rules, 
							is cheating or does not respect you, <strong>send a complaint</strong> to the moderators.</p>
					<p>Fake or useless complaints can be punished with warning or ban.</p>
					<a href="index.php?s=match&id=<?php echo $id;?>&action=report-abuse" class="report">Complaint</a>
					<?php obtenerComplainsPartido($id);?>
				</div>				
			</div>
		</div>
		<?php
	}else{
		?>
		<div id="content">
		<h1>An error has ocurred</h1>
		<div id="error">
			The selected match does not exist
		</div>
			<a href="index.php?s=tournaments" class="back">Go back</a>
	</div>
		<?php
	}
?>